package com.qf.carlikeboot.service.impl;


import com.google.common.base.Joiner;
import com.qf.carlikeboot.domain.User;
import com.qf.carlikeboot.mapper.UserMapper;
import com.qf.carlikeboot.service.UserService;
import com.qf.carlikeboot.utils.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        List<User> users = userMapper.selectByName(username);
        // 查到多个用户
        for (User user : users) {
            // 比较每个用户
            if (Objects.equals(password, user.getPassword())) {
                return user;
            }
        }
        return null;
    }

    /**
     * 用户喜欢/不喜欢那个名片
     *
     * @param uid  用户ID
     * @param cid  名片ID
     * @param like true:喜欢 false:不喜欢
     * @return 用户对象
     */
    @Override
    public User likeCard(Integer uid, Integer cid, Boolean like) {
        User user = userMapper.selectByPrimaryKey(Long.valueOf(uid));
        // 获取用户当前喜欢哪些名片  "1,2,3,4,5"
        String likedIds = user.getLiked();
        if (like) {
            // 喜欢名片 追加新的名片ID
            likedIds = Strings.isEmpty(likedIds) ? cid.toString() : likedIds + "," + cid;
        } else {
            String[] ids = likedIds.split(",");
            // 把喜欢的名片ID转换为list 方便移出操作
            List<String> list = Arrays.stream(ids).collect(Collectors.toList());
            list.remove(cid.toString());
            // {1,2,4,5} 重新转成字串
            likedIds = Joiner.on(",").join(list);
        }
        // 重新设置用户喜欢的liked属性
        user.setLiked(likedIds);
        // 需要更新到数据
        userMapper.updateByPrimaryKeySelective(user);
        return user;
    }

}
